/*
 * Projet industriel MBDS 2012 VAMP
 */
package com.vampmobile.android;

import java.net.URISyntaxException;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;

import com.vampmobile.android.db.VampREST;
import com.vampmobile.android.tools.GpsLocationTools;
import com.vampmobile.android.tools.ImageLoader;

public class VampApplication extends Application {
	private ImageLoader mImageLoader = null;
	public static final String TAG = "VampMobile";
	public static final String PREFS = "";
	private static VampApplication instance = null;
	private static Context context = null;
	private Boolean mReachable = null;
	private final static String SERVER_URL = "amlesas.dyndns.biz";

	public static VampApplication getInstance() {
		if (instance == null) {
			throw new IllegalStateException("Application not created yet!");
		}

		return instance;
	}

	@Override
	public void onCreate() {
		instance = this;
		context=getApplicationContext(); 
		if (android.os.Build.VERSION.SDK_INT > 9) { 
		      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
		      StrictMode.setThreadPolicy(policy); 
		    } 
	
		GpsLocationTools.initLocationManager();
		applyPreferences();
	}

	public static Context getAppContext() {
		return context;
	}

	/*
	 * web-services
	 */
	public void applyPreferences() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());

		// Set base-url from preferences
		String baseUrl = prefs.getString("dev_environment", "http://"+SERVER_URL);

		// Set default value if its empty (default values in preferences.xml are
		// not returned here).
		if (!prefs.contains("dev_environment")) {
			prefs.edit().putString("dev_environment", baseUrl).commit();
		}

		try {
			VampREST.setBaseUrl(baseUrl);
		} catch (URISyntaxException e) {
			Log.e(TAG, "Could not set base-URL: " + baseUrl);
		}
	}

	/**
	 * Check if the application is online.
	 * 
	 * @return boolean
	 */
	public boolean isOnline() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());

		if (prefs.getBoolean("force_offline", false)) {
			Log.d(TAG, "Prevented online access");
			return false;
		}

		mReachable = VampREST.isReachable();

		Log.d(TAG, "Reachable: " + mReachable);

		return mReachable;
	}

	/**
	 * Public accessor for image-loader, so all activities all use the same instance.
	 *
	 * @return ImageLoader
	 */
	public ImageLoader getImageLoader()
	{
		if (mImageLoader == null) {
			mImageLoader = new ImageLoader(this);
		}

		return mImageLoader;
	}
}
